<?php

namespace Service\CommodityService;

use Service\BaseService;
use App\Model\CommodityModel\CommodityOptimizationBbc;
use Hyperf\DbConnection\Db;
use App\Model\PssModel\Business;
use App\Model\CommodityModel\CommodityArchives;
use Service\Code\Normal;

/**
 * 商品优选池服务中心
 * @author chenshubo
 */
class CommodityPoolService extends BaseService
{
    //商品类型
    public $goodsType = [
        '0' => '一般贸易',
        '1' => '保税商品',
        '2' => '海外直邮',
    ];
    //百分率基数
    const BASE_PRICE_RATE       = 1.00;
    //小数点位数
    const BASE_SCALE_TYPE       = 4;
    //金额计算精度
    const BASE_FLOAT            = 3;

    /**
     * 获取商品优选池分页列表
     * @param array $param
     */
    public function getGoodsPoolList(array $param) 
    {
        $where      = $this->getWhereParameters($param);
        $limit      = $param['limit'] ?? 15;
        $page       = $param['page'] ?? 0;
        $bid        = $param['bid'] ? $param['bid'] : 0 ;
        $pageInfo   = $this
        ->getBestQuery($bid,self::getGoodsColumns(),$where)
        ->orderBy("cop.ID","asc")
        ->paginate($limit,['cop.*'], 'page', $page,true)
        ->toArray();

        $taxMode = 0;
        if( $param['bid'] > 0 ) {
            $config = Business::instance()->getUserInfoByBid($bid);
            $template_price_tpl = @json_decode($config['template_price_tpl'],true);
            $taxMode = $config['user_tax_mode'];
        }
        
        if( empty($template_price_tpl) ) {
            $template_price_tpl = [
                'price_settlement_rate' => '0.00',
                'price_rate' => '0.00',
                'price_market_rate' => '0.00',
            ];
        }
        
        foreach ($pageInfo['data'] as & $item )
        {
            $item['PriceControlTypeName'] = CommodityArchives::instance()->ControlPriceType[$item['PriceControlType']]??'未定义';
            $PriceScaleRule = @json_decode($item['PriceScaleRule'],true);
            $item['PriceScaleRule'] = !empty($PriceScaleRule) && $item['PriceRuleType'] == 1 ? $PriceScaleRule : $template_price_tpl;
            $item['SupplierCommodityTypeName'] = CommodityArchives::instance()->goods_types[$item['SupplierCommodityType']]??'未定义';
            $SpecList = @json_decode($item['SpecList'],true);
            //处理价格显示问题
            $SpecList = array_map(function( & $value) use ($taxMode, $item )
            {
                $SpecificationPrice = $value['SpecificationFreightPrice']??$value['SpecificationPrice'];
                $value['SpecificationPrice'] = $SpecificationPrice;
                $SpecNum = $value['SpecificationNum'];

                if( $item['PriceRuleType'] != 2 )
                {
                    $PriceScaleRule                 = $item['PriceScaleRule'];
                    $price_settlement_rate          = bcadd(bcdiv($PriceScaleRule['price_settlement_rate'],100,4),'1.00',4);
                    $price_rate                     = bcadd(bcdiv($PriceScaleRule['price_rate'],100,4),'1.00',4);
                    $price_market_rate              = bcadd(bcdiv($PriceScaleRule['price_market_rate'],100,4),'1.00',4);
                    $value['price_settlement_rate'] = $this->calcPriceFloat(bcmul($price_settlement_rate,$SpecificationPrice,3));
                    $value['price_rate']            = $this->calcPriceFloat(bcmul($price_rate,$SpecificationPrice,3));
                    $value['price_market_rate']     = $this->calcPriceFloat(bcmul($price_market_rate,$SpecificationPrice,3));

                    $singlePrice = bcdiv($value['price_settlement_rate'],$SpecNum,2);
                    //判断成本价是否触发高税率
                    $taxModeRate = $this->getTaxRate($singlePrice,$item['IsHaveTaxRate'],$item['TaxRate'],$item['ConSumptionTaxRate'],$item['ConSumptionPrice']);

                    $value['price_settlement_rate'] = $this->changeTaxPrice($value['price_settlement_rate'],$taxMode,$item['IsHaveTaxRate'],$taxModeRate,$item['TaxRate']);
                    
                }

                

                return $value;
            },$SpecList);
            $item['SpecList'] = $SpecList;
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$pageInfo);
    }

     /**
     * 价格计算向上取值
     * @param $price
     * @return string|null
     */
    public function calcPriceFloat($price)
    {
        $mulPrice = ceil(bcmul((string)$price,'100',1));
        return bcdiv((string)$mulPrice,'100',2);
    }

    // 停用
    // public function getTaxRate($price,$has_rate,$tax_rate,$con_tax_rate,$con_price)
    // {
    //     if($has_rate == 1){
    //         //商品单价默认都是含税 要把不含税的价格算出来
    //         $percent      = bcadd('1', $tax_rate, 4);
    //         $notTaxPrice  = bcdiv($price, $percent, 3);
    //         $notTaxPrice2 = bcmul($notTaxPrice, '100', 2);
    //         $notTaxPrice3 = ceil($notTaxPrice2);
    //         $price        = bcdiv((string)$notTaxPrice3, '100', 2);
    //     }

    //     if($con_tax_rate > 0 && $con_price > 0 && (bccomp((string)$price, (string)$con_price, 2) >= 0)){
    //         return $con_tax_rate;
    //     }
    //     return $tax_rate;
    // }

    public function getTaxRate($price,$has_rate,$tax_rate,$con_tax_rate,$con_price)
    {
        return BbcBestGoodsService::instance()->getTaxRate($price,$has_rate,$tax_rate,$con_tax_rate,$con_price);
    }

    /**
     * 根据填写的包邮模型来修改价格(停用)
     * @param $price
     * @param $taxMode
     * @param $isHaveTax
     * @param $taxRate
     * @return string
     */
    // public function changeTaxPrice($price,$taxMode,$isHaveTax,$taxRate,$lowTaxRate)
    // {
    //     $tax_rate = bcadd((string)$taxRate,'1.0000',4);
    //     $low_tax_rate = bcadd((string)$lowTaxRate,'1.0000',4);

    //     if($isHaveTax == 1){
    //         //商品含税
    //         if($taxMode == 2){
    //             //不含税价格
    //             $price = $this->calcPriceFloat(bcdiv((string)$price,$low_tax_rate,self::BASE_FLOAT));
    //         }else{
    //             if($taxRate != $lowTaxRate){
    //                 //含税价格
    //                 $price = $this->calcPriceFloat(bcdiv((string)$price,$low_tax_rate,self::BASE_FLOAT));
    //                 $price = $this->calcPriceFloat(bcmul((string)$price,$tax_rate,self::BASE_FLOAT));
    //             }    
    //         }
    //     }else{
    //         //商品不含税
    //         if($taxMode == 1){
    //             $price = $this->calcPriceFloat(bcmul((string)$price,$tax_rate,self::BASE_FLOAT));
    //         }
    //     }
    //     return $price;
    // }


       /**
     * 根据填写的包邮模型来修改价格
     * @param $price
     * @param $taxMode
     * @param $isHaveTax
     * @param $taxRate
     * @return string
     */
    public function changeTaxPrice($price,$taxMode,$isHaveTax,$taxRate,$lowTaxRate)
    {
        return BbcBestGoodsService::instance()->changeTaxPrice($price,$taxMode,$isHaveTax,$taxRate,$lowTaxRate);
    }


    
    /**
     * 获取字段
     */
    public function getGoodsColumns()
    {
        return [
            Db::raw("CONCAT(cop.ID,'') AS ID"),
            "cop.BuID",
            "cop.SKUCode",
            "cop.SupplierSKUCode",
            Db::raw("CONCAT(cop.SupplierSKUID,'') AS SupplierSKUID"),
            Db::raw("CONCAT(cop.StockInfoID,'') AS StockInfoID"),
            "stock.BatchNo",
            "stock.Number",
            "cop.BatchSpecMinSinglePrice",
            "cop.SpecList",
            "cop.IsPriceSet",
            "cop.IsSaleFirst",
            "cop.PriceScaleRule",
            "cop.PriceRuleType",
            "com.Name AS GoodsName",
            "com.BarCode",
            Db::raw("CONCAT(com.BrandID,'') AS BrandID"),
            "b.BrandName",
            Db::raw("IFNULL(class_f.ClassificationName,'') AS FirstClassificationName"),
            Db::raw("IFNULL(class_s.ClassificationName,'') AS SecondClassificationName"),
            Db::raw("IFNULL(class_t.ClassificationName,'') AS ThirdClassificationName"),
            "s.SupplierName",
            Db::raw("CONCAT(s.ID,'') AS SuppplierID"),
            "s.SupplierCode",
            "scb.IsFreeShipping",
            "scb.PriceControlType",
            "scb.LimitOrControlPrice",
            "scb.SupplierCommodityType",
            'scb.IsHaveTaxRate',
            'scb.TaxRate',
            'scb.ConSumptionTaxRate',
            'scb.ConSumptionPrice',
            'scb.IsCombineSupplierCommodity'
        ];
    }

    /**
     * 查询对象
     * @param int $BuID
     * @param array $columns
     * @param array $where
     */
    public function getBestQuery(int $BuID = 0, array $columns = [],array $where = [])
    {
        $table = CommodityOptimizationBbc::instance()->getTableByBuID($BuID)->getTable();
        return CommodityOptimizationBbc::instance()
        ->getTableByBuID($BuID)
        ->from("{$table} as cop")
        ->select($columns)
        ->leftjoin("commodityarchives_s2b as com","com.ID","=","cop.SkuID")
        ->leftjoin("brandinfo_s2b as b","b.ID","=","com.BrandID")
        ->leftjoin("classifyinfo_s2b as class_f","class_f.ID","=","com.FirstClassificationID")
        ->leftjoin("classifyinfo_s2b as class_s","class_s.ID","=","com.SecondClassificationID")
        ->leftjoin("classifyinfo_s2b as class_t","class_t.ID","=","com.ThirdClassificationID")
        ->join("stockinfo_s2b as stock","stock.ID","=","cop.StockInfoID")
        ->join("suppliercompany_s2b as s","s.ID","=","stock.SupplierCompanyID")
        ->join("suppliercommodity_s2b as scb","scb.ID","=","stock.SupplierCommodityID")
        ->whereRaw(implode(" AND ", $where))
        ->where('cop.CommodityStatus',1);
    }
    
    /**
     * 处理优选规则搜索
     * @param array $param
     */
    public function getWhereParameters( array $param = [] )
    {
        $where = [];
        $where[] = "cop.BuID = {$param['bid']} AND cop.IsInit=1";
    
        //供应商搜索
        if( !empty($param['CompanyIDs'])  && is_array($param['CompanyIDs'])) {
            $companyIds = implode(',', $param['CompanyIDs']);
            $where[] = "stock.SupplierCompanyID in ({$companyIds})";
        }
    
        //供应商SKU
        if( !empty($param['SupplierSKUCode']) ) {
            $where[] = "cop.SupplierSKUCode = '{$param['SupplierSKUCode']}'";
        }
    
        //SKUCode
        if( !empty($param['SKUCode']) ) {
            $where[] = "cop.SKUCode = '{$param['SKUCode']}'";
        }
    
        //BarCode
        if( !empty($param['BarCode']) ) {
            $where[] = "com.BarCode = '{$param['BarCode']}'";
        }
    
        //CommodityType
        if( isset($param['CommodityType']) && isset($this->goodsType[$param['CommodityType']]) ) {
            $where[] = "com.CommodityType = '{$param['CommodityType']}'";
        }
    
        //BrandIDs
        if(!empty($param['BrandIDs'])  && is_array($param['BrandIDs'])) {
            $BrandIDs = implode(',', $param['BrandIDs']);
            $where[] = "com.BrandID in ({$BrandIDs})";
        }
    
        //ClassIDs
        if(!empty($param['ClassIDs'])  && is_array($param['ClassIDs'])) {
            $ClassIDs = implode(',', $param['ClassIDs']);
            $where[] = "( com.FirstClassificationID in ({$ClassIDs}) or com.SecondClassificationID in ({$ClassIDs}) or com.ThirdClassificationID in ({$ClassIDs}))";
        }
    
        //IsFreeShipping
        if( isset($param['IsFreeShipping']) && in_array($param['IsFreeShipping'],['0','1']) ) {
            $where[] = "scb.IsFreeShipping = '{$param['IsFreeShipping']}'";
        }
    
        //PriceControlType
        if( isset($param['PriceControlType']) && in_array($param['PriceControlType'],['0','1','2']) ) {
            $where[] = "scb.PriceControlType = '{$param['PriceControlType']}'";
        }
    
        //PriceControlType
        if( isset($param['IsPriceSet']) && in_array($param['IsPriceSet'],['0','1']) ) {
            $where[] = "cop.IsPriceSet = '{$param['IsPriceSet']}'";
        }
    
        //GoodsName
        if( !empty($param['GoodsName'])) {
            $param['GoodsName'] = addslashes($param['GoodsName']);
            $where[] = "com.Name like '%{$param['GoodsName']}%'";
        }
    
        return $where;
    }
}